<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->layout_view = 'application_no_side_bar';
		$this->load->model('M_users');
		$this->load->library(array('form_validation','token'));
		$this->load->helper(array('url','form'));
		
		if($this->session->userdata('logged_in') == TRUE AND strtolower($this->uri->segment(2)) !== 'logout')
		{
			redirect($this->session->userdata('userType'));
		}
	}
	
	public function index()
	{
		redirect('auth/login');
	}
	
	private function _captcha()
	{
		$this->load->helper('captcha');
		$system_counted_hash = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
		$word = substr(md5($system_counted_hash),4,mt_rand(3,5));
		$vals = array(
			'word'	 => $word,
			'img_path'	 => './captcha/',
			'img_url'	 => base_url().'auth/captcha',
			'font_path'	 => './assets/_fonts/4.ttf',
			'img_width'	 => '150',
			'img_height' => 48,
			'expiration' => 7200
			);
		
		$cap = create_captcha($vals);
		$image['word'] = $cap['word'];
		$image['image'] ='<image src="'.base_url().'captcha/'.$cap['time'].'.jpg" class="captcha"/>';
		$image['link'] = './captcha/'.$cap['time'].'.jpg';

		return (object)$image;
	}

	/*12-6-12 Logs the user in the system*/
	function login()
	{
		$this->form_validation->set_error_delimiters('<span class="error_message">', '</span>');
		$this->view_data = $this->session->flashdata('logincred');
		$this->token->set_token();
		$this->layout_view = 'login';
		$captcha = $this->_captcha(); //generate captcha
		$this->session->set_flashdata('image_url',$captcha->link);
		$this->load->library('form_validation');
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['form_token'] = $this->token->get_token();
		$this->view_data['captcha_image'] = $captcha->image;

		$this->view_data['months'] = ['-- Select --','January','February','March','April','May','June','July','August','September','October','November','December'];
		
		if($this->input->post('login_student'))
		{
			$post = $this->input->post();
			$this->form_validation->set_rules('username[month]', 'username[month]', 'required|trim|htmlspecialchars|datechecker');
			$this->form_validation->set_rules('username[day]', 'username[day]', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('username[year]', 'username[year]', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('studentpassword', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('lastname', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('form_input_token', 'Form Token', 'trim|htmlspecialchars');

			//get captcha link from session
			$captcha_image_link = $this->session->flashdata('image_url');
			

			if($this->token->validate_token($this->input->post('form_input_token')))
			{
				//var_dump("here");
				if($this->form_validation->run() !== FALSE)
				{
					//hash the word
					$captcha_word = strtolower($this->session->userdata('word'));
					$sent_captcha_text = strtolower($this->input->post('captcha_text'));
				
					 print_r($captcha_word,$sent_captcha_text);
				
					if($captcha_word == $sent_captcha_text)
					{
						var_dump($captcha_word." ".$sent_captcha_text);
						if($this->M_users->verify_user($this->input->post()))
						{
							var_dump("in");
							$this->session->set_userdata('word',''); //destroy captcha from session
							@unlink($captcha_image_link);//delete captcha image from file
							$this->_msg('s','Welcome to student portal.','student');
						}else{
							var_dump("out");
							$this->session->set_flashdata('logincred',$post);
							$this->token->destroy_token();//destroy token
							$this->session->set_userdata('word','');//destroy captcha from session
							$message = '<div class="alert alert-danger">Invalid username/password combination.</div>';
							$this->_msg('x',$message,'auth/login/');
						}
					}else{
						$this->session->set_flashdata('logincred',$post);
						$this->token->destroy_token();
						$this->session->set_userdata('word','');
						@unlink($captcha_image_link);
						$message = '<div class="alert alert-danger">Invalid CAPTCHA entered.</div>';
						$this->_msg('x',$message,'auth/login/');
					}
				}else{
					$this->view_data['system_message'] = validation_errors();
				}
			}else{
				$this->token->destroy_token();
				$this->session->set_userdata('word','');
				@unlink($captcha_image_link);
				$message = '<div class="alert alert-danger">Invalid form submit detected.</div>';
				$this->_msg(FALSE,$message,'auth/login/');
			}
		}elseif($this->input->post('login_parent'))
		{
	
			$this->form_validation->set_rules('parent_username', 'username', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('parent_password', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('form_input_token', 'Form Token', 'trim|htmlspecialchars');

			//get captcha link from session
			$captcha_image_link = $this->session->flashdata('image_url');
			
			// pd($this->input->post());
			if($this->token->validate_token($this->input->post('form_input_token')))
			{
				if($this->form_validation->run() !== FALSE)
				{
					//hash the word
					$captcha_word = strtolower($this->session->userdata('word'));
					$sent_captcha_text = strtolower($this->input->post('captcha_text'));
				
					// pd($captcha_word,$sent_captcha_text);
				
					if($captcha_word == $sent_captcha_text)
					{
						$validation_result = $this->M_users->verify_parent($this->input->post());
						if($validation_result->status === true)
						{
							$this->session->set_userdata('word',''); //destroy captcha from session
							@unlink($captcha_image_link);//delete captcha image from file
							$this->_msg('s',$validation_result->log,'guardian');
						}else
						{
							$this->token->destroy_token();//destroy token
							$this->session->set_userdata('word','');//destroy captcha from session
							$message = '<div class="alert alert-danger">'.$validation_result->log.'</div>';
							$this->_msg('x',$message,'auth/login#parent');
						}
					}else{
						$this->token->destroy_token();
						$this->session->set_userdata('word','');
						@unlink($captcha_image_link);
						$message = '<div class="alert alert-danger">Invalid CAPTCHA entered.</div>';
						$this->_msg('x',$message,'auth/login#parent');
					}
				}else{
					pd(validation_errors());
				}
			}else{
				$this->token->destroy_token();
				$this->session->set_userdata('word','');
				@unlink($captcha_image_link);
				$message = '<div class="alert alert-danger">Invalid form submit detected.</div>';
				$this->_msg(FALSE,$message,'auth/login/#parent');
			}
		}else{
			$this->session->set_userdata('word',$captcha->word);
		}
	}

    function logout($add = '')
    {
		$usertype = $this->session->userdata('userType');
		$message = $this->_msg();
		
		$userdata = array(
			'userid' => '',
			'username' => '',
			'userType' => '',
			'e_f_name' => '',
			'e_l_name' => '',
			'e_m_name' => '',
			'logged_in' => FALSE
		);
		
		$this->session->set_userdata($userdata);

		if($message)
		{
			$this->_msg('s',$message,'auth/login#'.$add);
		}else{
			$message = '<div class="alert alert-info">You Are now logged out</div>';
			$this->_msg('n',$message,'auth/login#'.$add);
		}
    }
}